import ast
import logging

from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.generic.base import View

from system.models import Line, ApplyAccount
from utils.common.db_handle import get_account_list

logger = logging.getLogger(__name__)


@method_decorator(login_required, name='get')
class AccountApplyView(TemplateView):
    """申请账户页面"""

    template_name = 'system/apply.html'


@method_decorator(login_required, name='get')
class Account2LineView(View):
    """选择线路"""

    def get(self, request):
        line_list = Line.objects.values('province', 'city').annotate(nums=Count('province')).values('province',
                                                                                                    'city', 'nums')
        ret = dict(line_list=line_list)
        return render(request, 'system/account_account2line.html', ret)


@method_decorator(login_required, name='post')
class AccountCreateView(View):
    """创建账户"""

    def post(self, request):
        operator_choices = {'移动': 0, '联通': 1, '电信': 2, '不限': 2}
        ip_change_choices = {'on': 0, 'off': 1}
        """
        <QueryDict: {'title': ['通用客户端'], 'account_name': ['a'], 'account_num': ['1'], 'operator': ['不限'], 
        'ip_change': ['on'], 'date': ['2020-11-05'], 'expire_time': ['半年'], 'lines': ['北京北京,广东广州,广东深圳']}>

        """
        # 判断账户名是否存在
        account = ApplyAccount.objects.filter(name=request.POST.get('account_name'))
        if account:
            ret = {'code': 10030, 'msg': '账户已存在'}
            return JsonResponse(ret)

        try:
            # 写入数据库
            params = {
                'name': request.POST.get('account_name'),
                'client_type': request.POST.get('title'),
                'nums': request.POST.get('account_num'),
                'enable_lines': (request.POST.get('lines')).split(','),
                'operator': operator_choices.get(request.POST.get('operator')),
                'ip_change': ip_change_choices.get(request.POST.get('ip_change')),
                'expire_time': request.POST.get('date'),
                'user_id': request.user.id
            }

            ApplyAccount.objects.create(**params)
            ret = {'code': 0, 'msg': '创建成功'}
        except Exception as e:
            ret = {'code': 10031, 'msg': '创建失败'}
            logger.error('账户创建失败：%s', e)

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class AccountView(TemplateView):
    """账户视图"""

    template_name = 'system/account.html'


@method_decorator(login_required, name='get')
class AccountListView(View):
    """账户列表"""

    def get(self, request):
        ret = {'code': 0, 'msg': '请求成功', 'count': 0, 'data': []}
        user = request.user
        account_list = get_account_list(user.id)

        ret['data'] = account_list
        ret['count'] = len(account_list)

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class AccountCancelAuditView(View):
    """撤销审核"""

    def get(self, request):
        ret = {'code': 0, 'msg': '撤销成功'}
        try:
            id = request.GET.get('id')
            ApplyAccount.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            ret['code'] = 10029
            ret['msg'] = '撤销失败'

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class LineListView(View):
    """我的账户：用户线路"""

    def get(self, request):
        """获取上下文"""
        id = request.GET.get('id')
        account = ApplyAccount.objects.filter(id=id).first()
        enable_lines = ast.literal_eval(account.enable_lines)
        ret = dict(enable_lines=enable_lines)

        return render(request, 'system/lines.html', ret)
